/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.jsf.action;

import java.lang.reflect.*;

import javax.faces.context.*;

import org.aopalliance.intercept.*;
import org.metalframework.annotation.*;
import org.slf4j.*;

@InfrastructureComponent(ActionInvocationInterceptor.NAME)
public class ActionInvocationInterceptor implements MethodInterceptor {

	public static final String NAME = "actionInvocationInterceptor";
	
	private static final Logger logger = LoggerFactory.getLogger(ActionInvocationInterceptor.class);

	public Object invoke(MethodInvocation invocation) throws Throwable {
		if (FacesContext.getCurrentInstance() == null) { // If it is not a Faces method call, just pass it through
			return invocation.proceed();
		}
		
		logger.debug("Intercepting action invocation [{}]", invocation);

		Object target = invocation.getThis();
		Method method = invocation.getMethod();
		Object[] arguments = invocation.getArguments();
		Object returnValue = null;
		Throwable throwable = null;

		try {
			returnValue = invocation.proceed();
		} catch (Throwable t) {
			logger.error("Exception on action invocation", t);
			throwable = t;
		}
		
		ActionInvocation actionInvocation = new ActionInvocation(target, method, arguments, returnValue, throwable);
		ActionInvocationAccessor.setActionInvocation(actionInvocation);
		
		return returnValue;
	}

}
